<template>
  <div class="projectSelectPopup bg-white dark:bg-[var(--bg-2)]" v-loading="isLoading">
    <el-row class="h-full">
      <el-col :span="12" class="h-full">
        <div class="h-full border-r border-solid border-[var(--el-border-color-lighter)]">
          <treeList ref="treeListRef" v-model:inputModel="inputText" :inputProops="inputProops"
            :inputEvents="inputEvents" :treeProops="treeProops" :treeEvents="treeEvents">
            <template #input>
              <div class="tree-input">
                <el-input v-model.trim="inputText" v-bind="inputProops" v-on="inputEvents" />
              </div>
            </template>
            <template #page>
              <div class="p-[16px] h-[48px]">
                <el-checkbox class="!h-[16px]" v-model="showProjectType" label="数据包含下级单位"
                  :true-value="UNIT_TYPE_VIEW_Map.include" :false-value="UNIT_TYPE_VIEW_Map.current"
                  @change="viewsChange" />
              </div>
            </template>
          </treeList>
        </div>
      </el-col>
      <el-col :span="12" class="h-full">
        <div class="h-full treeList1">
          <treeList ref="treeListRef1" :treeProops="treeProops1" :treeEvents="treeEvents1"
            v-model:currentPage="treeListPage1.page" v-model:pageSizes="treeListPage1.limit" :pageProops="pageProops"
            :pageEvents="pageEvents">
            <template #input>
              <div class="tree-input">
                <el-input v-model.trim="projectInput" placeholder="请输入项目名称" @change="projectInputChange" />
              </div>
            </template>
          </treeList>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import treeList from "@/components/treeList/treeList.vue";
import { getProjectList } from "@/api/operate/project-management/projectManagement/index";
import { getUnitTree } from "@/api/operate/unity-management/index";
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
import { UNIT_TYPE_VIEW_Map } from "@/constant/index";
import { cloneDeep, storageLocal } from "@pureadmin/utils";
import { usePageReloadStoreHook } from "@/store/modules/pageReload";
import { getInfo } from "@/api/operate/project-management/projectManagement/index";
import { message } from "@/utils/message";
import { getUserProjectRole } from "@/api/operate/work-management/work-management";
import { setUserKey, userKey } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import { closePopover } from "@/components/customPopover";
const usePageVariablesStore = usePageVariablesStoreHook();
const operateInfo = ref(usePageVariablesStore.getOperate());
const isLoading = ref(false);
const defaultExpandedKeys = ref([]);
const defaultCheckedKeys = ref([]);
const treeRef = ref();
const treeListRef = ref();
const treeRef1 = ref();
const treeListRef1 = ref();
const checkedUnitId = ref(null);
const checkedUnitName = ref("");
const defultProjectList = () => [{ projectId: null, projectName: "全部项目" }];
const projectList = ref([]);
const showProjectType = ref(UNIT_TYPE_VIEW_Map.current);
const checkedProject = ref(null);
const checkedProjectName = ref("");
const checkedOpenFunc = ref([])
const props = {
  label: "unityName",
  value: "id",
  children: "childs",
  isLeaf: "isLeaf"
};
const props1 = {
  label: "projectName",
  value: "projectId"
};
const projectDefultSearch = () => {
  return {
    unityId: checkedUnitId.value,
    projectName: '',
    limit: 10,
    page: 1
  };
};
const treeListPage1 = ref(projectDefultSearch());
const pageProops = ref({
  layout: "prev, pager, next",
  total: 0,
  background: true,
  "pager-count": "3"
});
const projectInput = ref("");
const inputText = ref("");
const unityList = ref([]);

onMounted(() => {
  defaultExpandedKeys.value = (operateInfo.value.checkedUnitPath + "")
    .split("-")
    .map(Number);
  console.log("defaultExpandedKeys.value", defaultExpandedKeys.value);
  defaultCheckedKeys.value = [operateInfo.value.checkedUnitId];
  checkedUnitId.value = operateInfo.value.checkedUnitId;
  checkedUnitName.value = operateInfo.value.unityName;
  checkedProject.value = operateInfo.value.checkedProject;
  checkedOpenFunc.value = operateInfo.value.openFunc
  checkedProjectName.value = operateInfo.value.projectName;
  showProjectType.value = operateInfo.value.views;
  treeRef.value = treeListRef.value.getTreeRef();
  treeRef1.value = treeListRef1.value.getTreeRef();
  loadProjectList();
  loadUnitTree();
  treeRef.value.setCheckedKeys([checkedUnitId.value]);
  treeRef.value.setCurrentKey(checkedUnitId.value);
  treeRef.value.setExpandedKeys(defaultExpandedKeys.value);
  treeRef1.value.setCurrentKey(operateInfo.value.checkedProject);
});
const loadUnitTree = () => {
  isLoading.value = true;
  getUnitTree()
    .then(res => {
      unityList.value = res.result.data;
      // for (let i = 0; i < 1000; i++) {
      //     unityList.value.push(res.result.data)
      // }
    })
    .finally(() => {
      isLoading.value = false;
    });
};
const handleNodeClick = data => {
  // console.log('handleNodeClick', data);
  treeRef.value.setCheckedKeys([data.id]);
  checkedUnitId.value = data.id;
  checkedUnitName.value = data.unityName;
  loadProjectList();
};
const handleNodeClick1 = data => {
  console.log(data);
  checkedProject.value = data.projectId;
  checkedOpenFunc.value = data.openFunc
  checkedProjectName.value = data.projectName;
  setCheckedProject();
};
const handleCheckChange = (data, isChecked) => {
  // console.log('handleCheckChange', data, isChecked);
  treeRef.value.setCheckedKeys([data.id]);
  treeRef.value.setCurrentKey(data.id);
  checkedUnitId.value = data.id;
  checkedUnitName.value = data.unityName;
  loadProjectList();
};
const loadProjectList = () => {
  isLoading.value = true;
  if (checkedUnitId.value) {
    treeListPage1.value.unityId = checkedUnitId.value;
    treeListPage1.value.projectName = projectInput.value;
    getProjectList(treeListPage1.value).then(res => {
      projectList.value = defultProjectList();
      // projectList.value = []
      projectList.value.push(...res.result.data);
      pageProops.value.total = res.result.total;
    }).finally(() => {
      isLoading.value = false;
    });
    checkedProject.value = null;
    checkedOpenFunc.value = []
    checkedProjectName.value = null;
    treeRef1.value.setCurrentKey(null);
  }
};
const setCheckedProject = () => {
  let copyOperateInfo = cloneDeep(usePageVariablesStore.operate)
  usePageVariablesStore.setOperate({
    checkedUnitPath: getCheckedPath(treeRef.value.getNode(checkedUnitId.value)),
    checkedUnitId: checkedUnitId.value,
    views: showProjectType.value,
    checkedProject: checkedProject.value != 0 ? checkedProject.value : null,
    unityName: checkedUnitName.value,
    projectName: checkedProjectName.value,
    openFunc: checkedProject.value != 0 ? checkedOpenFunc.value : []
  });
  if (checkedProject.value && checkedProject.value != 0) {
    getInfo({ projectId: checkedProject.value }).then(res => {
      if (res.result.expireStatus == 2) {
        message('项目已过期', { type: 'warning' })
      }
      getUserProjectRole().then(res1 => {
        let userInfo = storageLocal().getItem(userKey).userInfo;
        if (userInfo.roles) {
          userInfo.roles.operate = res1.result.data
        } else {
          userInfo.roles = {
            operate: res1.result.data
          }
        }
        setUserKey(userInfo.nickname, res1.result.data, userInfo);
        usePageVariablesStore.operateProjectInfo = res.result;
        if([ '/error/expire', '/error/noProjectSelected'].includes(router.currentRoute.value.fullPath)){
          resetRouter()
        }else{
          resetRouter(router.currentRoute.value)
        }
        usePageReloadStoreHook().reloadPages()
        closePopover()
      }).catch(() => {
        message('获取项目权限失败', { type: 'error' })
        usePageVariablesStore.setOperate(copyOperateInfo)
      })
    }).catch(() => {
      usePageVariablesStore.setOperate(copyOperateInfo)
    })
  } else {
    let userInfo = storageLocal().getItem(userKey).userInfo;
    if (userInfo.roles) {
      userInfo.roles.operate = []
    } else {
      userInfo.roles = {
        operate: []
      }
    }
    setUserKey(userInfo.nickname, userInfo.roles, userInfo);
    resetRouter(null, false)
    usePageVariablesStore.operateProjectInfo = null;
    usePageReloadStoreHook().reloadPages()
    closePopover()
  }
};
const getCheckedPath = node => {
  console.log(node);
  if (node?.parent) {
    return getCheckedPath(node.parent) + "-" + node.data.id;
  } else {
    return node.data.id;
  }
};
const inputChange = val => {
  // console.log('aaaaaasdsaddasdadaaaa', val);
  treeRef.value.filter(val);
};
const filterNode = (value, data) => {
  // console.log(data);
  if (!value) return true;
  return data.unityName.includes(value);
};
const pageChange = () => {
  loadProjectList();
};
const projectInputChange = () => {
  treeListPage1.value = projectDefultSearch();
  loadProjectList();
};

const viewsChange = () => {
  let info = cloneDeep(usePageVariablesStore.getOperate());
  info.views = showProjectType.value;
  usePageVariablesStore.setOperate(info);
  loadProjectList();
  usePageReloadStoreHook().reloadPages()
  closePopover()
};

const treeProops = ref({
  props: props,
  // load: loadNode,
  // lazy: true,
  itemSize: "46",
  data: unityList,
  checkStrictly: true,
  highlightCurrent: false,
  // showCheckbox: true,
  expandOnClickNode: false,
  nodeKey: "id",
  defaultExpandedKeys: defaultExpandedKeys,
  defaultCheckedKeys: defaultCheckedKeys,
  "filter-method": filterNode
});
const treeProops1 = ref({
  props: props1,
  // load: loadNode,
  // lazy: true,
  itemSize: "46",
  data: projectList,
  checkStrictly: true,
  highlightCurrent: false,
  nodeKey: "projectId"
});
const treeEvents = {
  nodeClick: handleNodeClick,
  checkChange: handleCheckChange
};
const treeEvents1 = {
  nodeClick: handleNodeClick1
};
const inputProops = {
  placeholder: "请输入单位名称"
};
const inputEvents = {
  change: inputChange
};
const pageEvents = {
  change: pageChange
};
function getRef() {
  return treeRef.value;
}

defineExpose({
  getRef,
  setCheckedProject
});
</script>
<style lang="scss" scoped>
.projectSelectPopup {
  position: relative;
  height: 100%;
  width: 600px;

  ::v-deep(.el-tree-node__content) {
    .el-tree-node__expand-icon {
      padding: 16px;
    }

    .el-checkbox {
      margin-left: -6px;
    }
  }

  .treeList1 {
    ::v-deep(.el-tree-node__content) {
      padding-left: 16px !important;

      .el-tree-node__expand-icon {
        display: none;
      }
    }

    ::v-deep(.tree-page) {
      padding: 16px;
      // display: flex;
      // justify-content: center;
    }
  }

  .tree-input {
    margin: 16px;
  }
}
</style>
